package kd.hc.ecco;

import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.AddValidatorsEventArgs;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
import kd.bos.entity.validate.ValidateResultCollection;
import kd.bos.exception.KDBizException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.DeleteServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.hc.utils.BusinessDataServiceHelperExt;
import kd.hc.utils.JsonUtil;
import kd.hc.utils.OperationServiceUtil;
import kd.sdk.plugin.Plugin;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 目标成本 服务插件
 */
public class TargetCostBillServicePlugIn extends AbstractOperationServicePlugIn implements Plugin {


    @Override
    public void endOperationTransaction(EndOperationTransactionArgs e) {
        super.endOperationTransaction(e);
        String operationKey = e.getOperationKey();
        switch (operationKey) {
            case "audit"://审核生成合约规划
                genContractPlanning(e.getDataEntities());
                break;
            case "unaudit"://反审核删除合约规划和合约包
                deleteContractPlanning(e.getDataEntities());
                break;
            case "dochage"://目标成本变更
                dochage(e.getDataEntities());
                break;
            case "dogenContractPlanning"://重新生成合约规划
                dogenContractPlanning(e.getDataEntities());
                break;
        }
    }

    public void dochage(DynamicObject[] dataEntities) {
        if (dataEntities != null && dataEntities.length >= 1) {
            if (dataEntities.length >= 2) {
                throw new KDBizException("目标成本变更不能同时变更多个目标成本!");
            }
            DynamicObject dataEntity = dataEntities[0];
            String id = dataEntity.getString("id");
            DynamicObject targetCost = BusinessDataServiceHelper.loadSingle(id, "hc95_target_cost");
            //判断是否是已审核状态
            String billstatus = targetCost.getString("billstatus");
            if (!"C".equals(billstatus)) {
                throw new KDBizException("非已审核状态不能变更!");
            }
            ValidateResultCollection validateResult = this.operationResult.getValidateResult();
            //判断是否有 暂存 已提交的变更单有直接打开
            //判断合约包是被引用
        } else {
            throw new KDBizException("请先选中行!");
        }
    }

    public void genContractPlanning(DynamicObject[] dataEntities) {
        Date dateCurrent = new Date();
        MainEntityType entityType = EntityMetadataCache.getDataEntityType("hc95_contract_planning");
        for (DynamicObject dataEntity : dataEntities) {
            String id = dataEntity.getString("id");
            //来源目标成本
            DynamicObject targetCost = BusinessDataServiceHelper.loadSingle(id, "hc95_target_cost");
            DynamicObjectCollection entryentity = targetCost.getDynamicObjectCollection("hc95_tree_entryentity");//明细信息
            DynamicObject hc95_project_number = targetCost.getDynamicObject("hc95_project_number");//项目编码
            String hc95_version = targetCost.getString("hc95_version");
            DynamicObject org = targetCost.getDynamicObject("org");
            String projectNumber = targetCost.getString("billno");
            //目标
            DynamicObject contractPlan = new DynamicObject(entityType);//合约规划
            DynamicObjectCollection hc95_costen = contractPlan.getDynamicObjectCollection("hc95_costen");
            //标题
            contractPlan.set("hc95_project_number", hc95_project_number);
            contractPlan.set("hc95_mbcbbb", hc95_version);
            contractPlan.set("hc95_billdate", dateCurrent);
            contractPlan.set("org", org);
            contractPlan.set("billstatus", "A");
            if (entryentity != null && entryentity.size() >= 1) {
                List<Map<String, Object>> hyhList = new ArrayList<>();
                AtomicReference<BigDecimal> zxmbcbSum = new AtomicReference<>(BigDecimal.ZERO);
                List<DynamicObject> rankEnOne = entryentity.stream().filter(f1 -> f1.getString("hc95_rank_en").equals("1")).collect(Collectors.toList());//一级目标成本项
                rankEnOne.forEach(item -> {
                    String rootId = item.getString("id");
                    String rootLongId = item.getString("hc95_longid_en");
                    DynamicObject costItemEn = item.getDynamicObject("hc95_cost_item_en");
                    if (costItemEn != null) {
                        int level = costItemEn.getInt("level");
                        if (1 == level) {
                            //List<DynamicObject> sourceHyB = entryentity.stream().filter(f1 -> f1.getString("hc95_longid_en").startsWith(rootLongId + ".") && f1.getBoolean("hc95_isschyb")).collect(Collectors.toList());
                            //所以三级不包含大劳务分包三级 加上二级大劳务分包 CBLX-000010
                            List<DynamicObject> sourceHyB = entryentity.stream()
                                    .filter(f1 -> f1.getString("hc95_longid_en").startsWith(rootLongId + "."))
                                    .filter(f2 -> f2.getString("hc95_rank_en").equals("3") || f2.getDynamicObject("hc95_cost_item_en").getString("number").equals(Constant.DLWFB_NUMBER))
                                    .collect(Collectors.toList());
                            DynamicObject dynamicObject = hc95_costen.addNew();
                            //合约包
                            dynamicObject.set("hc95_cost_typenumber", costItemEn);
                            dynamicObject.set("hc95_textfield_cblx", rootId);
                            for (DynamicObject itemHY : sourceHyB) {
                                int rank = itemHY.getInt("hc95_rank_en");
                                String threeLevelId = itemHY.getString("id");
                                DynamicObject itemThree = itemHY.getDynamicObject("hc95_cost_item_en");
                                DynamicObject parent = itemThree.getDynamicObject("parent");
                                if (rank == 3 && parent.getString("number").equals(Constant.DLWFB_NUMBER)) {
                                    continue;
                                }
                                BigDecimal hc95_zxmbcb = itemHY.getBigDecimal("hc95_zxmucbe_sum_en");
                                HashMap<String, Object> hybenRow = new HashMap<>();
                                hybenRow.put("hc95_hyb", itemThree);
                                hybenRow.put("hc95_zxmbcb", hc95_zxmbcb);
                                hybenRow.put("hc95_hyghje", hc95_zxmbcb);
                                hybenRow.put("hc95_mbcbhid", threeLevelId);
                                hyhList.add(hybenRow);
                                zxmbcbSum.set(zxmbcbSum.get().add(hc95_zxmbcb));
                            }
                        }
                    }
                });
                contractPlan.set("hc95_mbcbje", zxmbcbSum);
                contractPlan.set("billno", "HYGH_" + projectNumber);
                OperationResult result = OperationServiceUtil.saveAndSubmitAndAudit("hc95_contract_planning", contractPlan);
                //生成合约包
                genContractPackage(result, targetCost, hyhList);
            }

        }
    }

    public void deleteContractPlanning(DynamicObject[] dataEntities) {
        Date dateCurrent = new Date();
        for (DynamicObject dataEntity : dataEntities) {
            String id = dataEntity.getString("id");
            //来源目标成本
            DynamicObject targetCost = BusinessDataServiceHelper.loadSingle(id, "hc95_target_cost");
            DynamicObject project = targetCost.getDynamicObject("hc95_project_number");//项目编码
            Object projectId = project.getPkValue();
            //删除该项目的合约包
            OperationServiceUtil.deleteByOneCondition("hc95_contract_package", "hc95_project_code", projectId, true);
            //删除该项目的合约规划
            OperationServiceUtil.deleteByOneCondition("hc95_contract_planning", "hc95_project_number", projectId, true);
        }
    }

    public void dogenContractPlanning(DynamicObject[] dataEntities) {
        deleteContractPlanning(dataEntities);
        genContractPlanning(dataEntities);
    }

    /**
     * 生成合约包
     *
     * @param result
     */
    public void genContractPackage(OperationResult result, DynamicObject targetCost, List<Map<String, Object>> hyhList) {
        Object billId = result.getSuccessPkIds().get(0);

        for (Map<String, Object> itemHY : hyhList) {
            String hc95_mbcbhid = (String) itemHY.get("hc95_mbcbhid");//目标成本行id
            DynamicObject hyb = (DynamicObject) itemHY.get("hc95_hyb");//成本类型
            BigDecimal hc95_zxmbcb = (BigDecimal) itemHY.get("hc95_zxmbcb");

            DynamicObject currencyCNY = BusinessDataServiceHelperExt.loadCurrencyCNY();
            MainEntityType entityType = EntityMetadataCache.getDataEntityType("hc95_contract_package");
            //获取合约规划单据信息 来源单据
            DynamicObject org = targetCost.getDynamicObject("org");//组织
            DynamicObject project = targetCost.getDynamicObject("hc95_project_number");//项目

            //
            BigDecimal hc95_ysmbcbe = BigDecimal.ZERO;//原始目标成本额
            BigDecimal hc95_hyghje = hc95_zxmbcb;//合约规划金额
            BigDecimal hc95_byyhtje = BigDecimal.ZERO;//被引用合同金额
            BigDecimal hc95_byyzbje = BigDecimal.ZERO;//被引用招标金额
            String hc95_byyhtbm = "";//被引用合同编码
            String hc95_byyzbbm = "";//被引用招标编码

            DynamicObject contractPackageNew = new DynamicObject(entityType);
            contractPackageNew.set("createorg", org);
            contractPackageNew.set("useorg", org);
            contractPackageNew.set("hc95_project_code", project);
            contractPackageNew.set("hc95_cost_type", hyb);
            contractPackageNew.set("number", project.getString("number") + "_" + hyb.getString("number"));
            contractPackageNew.set("name", hyb.getString("name"));
            contractPackageNew.set("hc95_ysmbcbe", hc95_ysmbcbe);
            contractPackageNew.set("hc95_zxmbcb", hc95_zxmbcb);
            contractPackageNew.set("hc95_hyghje", hc95_hyghje);
            contractPackageNew.set("status", "A");
            contractPackageNew.set("enable", "1");
            contractPackageNew.set("hc95_currency", currencyCNY);
            contractPackageNew.set("hc95_byyhtje", hc95_byyhtje);
            contractPackageNew.set("hc95_byyzbje", hc95_byyzbje);
            contractPackageNew.set("hc95_byyhtbm", hc95_byyhtbm);
            contractPackageNew.set("hc95_byyzbbm", hc95_byyzbbm);
            contractPackageNew.set("hc95_hyghid", billId);
            contractPackageNew.set("hc95_mbcbhid", hc95_mbcbhid);
            OperationServiceUtil.saveAndSubmitAndAudit("hc95_contract_package", contractPackageNew);

            //生成合约包基础资料

        }
    }

}